package com.wtwd.wtwddevice.listener.appMsg;

import com.alibaba.fastjson.JSONArray;
import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.*;
import com.wtwd.device.model.SetAlarm;
import com.wtwd.device.model.WPhone;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.StringUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.model.entity.DeviceAlarmInfo;
import com.wtwd.wtwddevice.model.entity.DeviceWPhone;
import com.wtwd.wtwddevice.mq.PushAppMsgService;
import com.wtwd.wtwddevice.service.IDeviceSendService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IDeviceWPhoneService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * app设置通讯录
 */
@MsgType(MsgTypeEnum.APP_W_PHL)
@Component
public class AppSetWPHLHandler implements IMsgHandler {

    @Resource
    private IDeviceService deviceService;

    @Resource
    private IDeviceSendService deviceSendService;

    @Resource
    private PushAppMsgService msgService;

    @Resource
    private IDeviceWPhoneService deviceWPhoneService;

    @Override
    public void handleMsg(MessageBase messageBase) {
        AppProtocol appProtocol = messageBase.getAppProtocol();
        JSONArray data = (JSONArray) appProtocol.getData();
        List<WPhone> wPhones = data.toJavaList(WPhone.class);
        String body = "";
        for (int i = 0; i < wPhones.size(); i++) {
            if (i == 0) {
                body += wPhones.get(i).serialization();
            } else {
                body += SeparatorConstant.CMD_BODY_SEGMENTATION + wPhones.get(i).serialization();
            }
        }
        Long deviceId = deviceService.getDeviceIdByImei(appProtocol.getImei());
        String number = deviceSendService.generateNumber(appProtocol.getImei());
        WTProtocol wtProtocol = WTProtocol.builder()
                .imei(appProtocol.getImei())
                .cmdName(MsgTypeEnum.W_PHL.getCmdName())
                .body(StringUtils.isEmpty(body) ? "0" : body)
                .bodyLength(body.length())
                .number(number)
                .build();
        if (deviceSendService.sendMsgDevice(wtProtocol)) {//如果为fase直接告知app端设置失败
            //存储号码，标记状态
            List<DeviceWPhone> deviceWPhones = new ArrayList<>();
            for (WPhone wPhone : wPhones) {
                DeviceWPhone deviceWPhone = new DeviceWPhone();
                BeanUtils.copyProperties(wPhone,deviceWPhone);
                deviceWPhone.setState(CmdStateEnum.SENDING.getState());
                deviceWPhone.setDeviceId(deviceId);
                deviceWPhone.setNumber(number);
                deviceWPhone.setIsRemove(Constant.NORMAL);
                deviceWPhones.add(deviceWPhone);
            }
            deviceWPhoneService.synchronization(deviceId, number, deviceWPhones);
        } else {
            AppProtocol protocol = AppProtocol.builder()
                    .imei(wtProtocol.getImei())
                    .cmdName(MsgTypeEnum.APP_W_PHL.getCmdName())
                    .state(AnswerStateEnum.ABNORMAL.getState())
                    .data(null)
                    .build();
            msgService.pushToDevice(messageBase.getForm(),
                    MessageBase.builder()
                            .appProtocol(protocol)
                            .build()
            );
        }

    }

//    public static void main(String[] args) {
//        ArrayList<WPhone> wPhones = new ArrayList<>();
//        WPhone wPhone = new WPhone();
//        wPhone.setPhone("13669061320");
//        wPhone.setName("俊俊");
//        wPhone.setSex(0);
//        wPhones.add(wPhone);
//        WPhone wPhone1 = new WPhone();
//        wPhone1.setPhone("13669061321");
//        wPhone1.setName("俊俊pp");
//        wPhone1.setSex(0);
//        wPhones.add(wPhone1);
//        String s = JSONArray.toJSONString(wPhones);
//        System.out.println(s);
//    }
    /**
     * 将十六进制字符串转换为字节数组
     * @param hex 十六进制字符串
     * @return 字节数组
     */
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    /**
     * 将十六进制字符串转换为原始字符串（假设 UTF-8 编码）
     * @param hex 十六进制字符串
     * @return 原始字符串
     */
    public static String hexToString(String hex) {
        byte[] bytes = hexStringToByteArray(hex);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static String stringToHex(String input) {
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        String hexString = "e5b08fe8b596";
        String originalString = hexToString(hexString);
        System.out.println("原始字符串: " + originalString);
        System.out.println(stringToHex(originalString));
    }
}
